package edu.ynu.se.xiecheng.achitectureclass.device.controller;

import edu.ynu.se.xiecheng.achitectureclass.common.controller.LogicController;
import edu.ynu.se.xiecheng.achitectureclass.device.dao.DeviceDAO;
import edu.ynu.se.xiecheng.achitectureclass.device.entity.Device;
import edu.ynu.se.xiecheng.achitectureclass.device.service.DeviceService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Tag(name = "设备管理", description = "设备管理相关接口")
@RestController
@RequestMapping("/api/devices")
@CrossOrigin
@RequiresAuthentication
public class DeviceController extends LogicController<DeviceService, DeviceDAO, Device, Long> {

    private static final Logger logger = LoggerFactory.getLogger(DeviceController.class);

    @Autowired
    public DeviceController(DeviceService service) {
        super(service);
    }

    @Operation(summary = "根据大棚编号获取设备列表")
    @GetMapping("/greenhouse/{greenhouseNumber}")
    public ResponseEntity<?> getDevicesByGreenhouseNumber(@PathVariable String greenhouseNumber) {
        try {
            List<Device> devices = service.getSoilDevices(greenhouseNumber);
            return ResponseEntity.ok(devices);
        } catch (Exception e) {
            logger.error("获取设备列表失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest()
                    .body(Map.of(
                            "success", false,
                            "message", "获取设备列表失败: " + e.getMessage()
                    ));
        }
    }

    @Operation(summary = "根据设备编号获取设备")
    @GetMapping("/number/{deviceNumber}")
    public Device getDeviceByNumber(@PathVariable String deviceNumber) {
        return service.getDeviceByNumber(deviceNumber);
    }

    @Operation(summary = "根据设备类别获取设备列表")
    @GetMapping("/category/{category}")
    public List<Device> getDevicesByCategory(@PathVariable String category) {
        return service.getDevicesByCategory(category);
    }
}
